import os
import logging
from logging.handlers import RotatingFileHandler

# 全局日志对象
logger = None

def init_logger(app):
    """初始化日志配置"""
    global logger
    
    # 配置日志级别
    log_level = app.config.get('LOG_LEVEL', 'INFO')
    numeric_level = getattr(logging, log_level.upper(), None)
    if not isinstance(numeric_level, int):
        numeric_level = logging.INFO
    
    # 创建日志目录
    log_dir = os.path.join(app.root_path, '..', 'logs')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    
    # 创建日志文件路径
    log_file = os.path.join(log_dir, app.config.get('LOG_FILE', 'app.log'))
    
    # 配置日志格式
    formatter = logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    )
    
    # 配置文件处理器
    file_handler = RotatingFileHandler(
        log_file, maxBytes=10485760, backupCount=10
    )
    file_handler.setFormatter(formatter)
    file_handler.setLevel(numeric_level)
    
    # 配置控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    console_handler.setLevel(numeric_level)
    
    # 配置应用日志
    app.logger.addHandler(file_handler)
    app.logger.addHandler(console_handler)
    app.logger.setLevel(numeric_level)
    
    # 创建全局日志器
    logger = logging.getLogger('app')
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    logger.setLevel(numeric_level)
    
    # 设置其他模块的日志级别
    logging.getLogger('werkzeug').setLevel(logging.WARNING)

def get_logger(name=None):
    """获取日志对象"""
    global logger
    if logger is None:
        logger = logging.getLogger('app')
    
    if name:
        return logging.getLogger(name)
    return logger